package com.chapter.sample.juc.automics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyNumber {
    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus() {
        atomicInteger.incrementAndGet();
    }
}

public class AtomicIntegerDemo {
    public static final int SIZE_ = 50;
    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(50);
        for (int i = 1; i <= SIZE_; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= 1000; j++) {
                        myNumber.addPlusPlus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }

            }, "thread:" + i).start();
        }
        //起阻拦索的作用，保证业务彻底完成了，完成一个 “-1“；最终彻底完成后返回
        countDownLatch.await();
        //TimeUnit.SECONDS.sleep(1);
        //如果直接打印输出，会导致myNumber.atomicInteger.get()值比实际小；因为main线程太快了，计算是完成了的（50000），输出的问题
        System.out.println(Thread.currentThread().getName() + " ---- result: " + myNumber.atomicInteger.get());
    }
}
